package com.atguigu.spzx.gateway.config;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import com.atguigu.spzx.model.common.ResultCodeEnum;
import jakarta.annotation.Resource;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * title:
 * author: zgl
 * date: 2024/1/17
 * description：
 */
@Configuration
public class GlobalFilter implements org.springframework.cloud.gateway.filter.GlobalFilter, Ordered {
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //是否要验证登录状态
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        AntPathMatcher matcher = new AntPathMatcher();
        //no
        if(!matcher.match("/**/auth/**",path)){
            return chain.filter(exchange);
        }
        //yes
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token) || !redisTemplate.hasKey("spzx:user:login" + token)){
            ServerHttpResponse response = exchange.getResponse();
            //响应头
            response.getHeaders().add("content-type", MediaType.APPLICATION_JSON_UTF8_VALUE);
            //响应体
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("code", ResultCodeEnum.LOGIN_STATUS_ERROR.getCode());
            jsonObject.addProperty("message",ResultCodeEnum.LOGIN_STATUS_ERROR.getMessage());
            String jsonStr = jsonObject.toString();
            DataBuffer buffer = response.bufferFactory().wrap(jsonStr.getBytes());
            return response.writeWith(Mono.just(buffer));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
